package Top200;

import java.util.*;

/**
 * @author zhangmin
 * @create 2022-02-22 11:59
 * 给每个字符串进行编码，使用排序
 */
public class groupAnagrams49 {
    public List<List<String>> groupAnagrams(String[] strs) {
        int n=strs.length;
        List<List<String>> res=new LinkedList<>();
        if (n==1){
            List<String> list=new LinkedList<>();
            list.add(strs[0]); res.add(list);
            return res;
        }

        HashMap<String,LinkedList<String>> map=new HashMap<>();
        for (String str:strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String s="";
            for (char c: chars) {
                s+=c;
            }
            LinkedList<String> linkedList = map.getOrDefault(s, new LinkedList<>());
            linkedList.addLast(str);
            map.put(s,linkedList);
        }
        for (Map.Entry<String,LinkedList<String>> entry:map.entrySet()) {
            res.add(entry.getValue());
        }
        return res;
    }
}
